#!/usr/bin/env python3
# -*- coding: utf-8 -*-

__author__ = 'Liu DengFeng'

import base64
import numpy as np
import cv2
import io
from PIL import Image

# 保存处理后的图片
def save_dealed_img(name, cv2_img):
    output_path = './imageSamples/' + name + '.png'
    cv2.imwrite(output_path, cv2_img)  # 保存图片

# base64图片数据 转为 cv2能用的图片对象
def b64_cv2(b64_str):
    img_bytes = base64.b64decode(b64_str)
    nparr = np.frombuffer(img_bytes, np.uint8)
    #IMREAD_COLOR,IMREAD_GRAYSCALE,IMREAD_UNCHANGED,IMREAD_ANYCOLOR,IMREAD_ANYDEPTH
    cv2_image = cv2.imdecode(nparr, cv2.IMREAD_UNCHANGED)
    return cv2_image

# 获取内容轮廓在图片中的位置数据
def get_target(base64_str):
    image = Image.open(io.BytesIO(base64.decodebytes(bytes(base64_str, "utf-8"))))
    w, h = image.size
    starttx = 0
    startty = 0
    end_x = 0
    end_y = 0
    for x in range(w):
        for y in range(h):
            p = image.getpixel((x, y))
            if p[-1] == 0:
                if startty != 0 and end_y == 0:
                    end_y = y

                if starttx != 0 and end_x == 0:
                    end_x = x
            else:
                if startty == 0:
                    startty = y
                    end_y = 0
                else:
                    if y < startty:
                        startty = y
                        end_y = 0
        if starttx == 0 and startty != 0:
            starttx = x
        if end_y != 0:
            end_x = x
    return image.crop([starttx, startty, end_x, end_y]), starttx, startty

# 算法匹配图片位置
def generate_distance(slide_b64, bg_b64):
    slide_image = b64_cv2(slide_b64)
    slide_image = cv2.Canny(slide_image, 255, 255)
 
    bg_image = b64_cv2(bg_b64)
    bg_image = cv2.pyrMeanShiftFiltering(bg_image, 5, 50)
    bg_image = cv2.Canny(bg_image, 255, 255)
 
    # TM_SQDIFF,TM_SQDIFF_NORMED,TM_CCORR,TM_CCORR_NORMED,TM_CCOEFF,TM_CCOEFF_NORMED
    # TM_CCORR,TM_CCORR_NORMED,TM_CCOEFF,TM_CCOEFF_NORMED
    matching_method = cv2.TM_CCOEFF
    result = cv2.matchTemplate(bg_image, slide_image, matching_method)
    min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(result)

    target, target_x, target_y = get_target(slide_b64)
    h, w = slide_image.shape[:2]
    bottom_right = (max_loc[0] + w, max_loc[1] + h)

    return {"target_x": target_x,
            "target_y": target_y,
            "target": [int(max_loc[0]), int(max_loc[1]), int(bottom_right[0]), int(bottom_right[1])]}